package com.kalenchuk.service.impl;

import java.util.List;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.kalenchuk.dao.TransformatorDao;
import com.kalenchuk.model.Transformator;
import com.kalenchuk.service.TransformatorService;
import com.kalenchuk.util.Utils;

@Service("transformatorService")
@Transactional
public class TransformatorServiceImpl implements TransformatorService{
	
	@Autowired
	private TransformatorDao transformatorDao;

	
	public void fillTransformatorTable(JTable table) {
		List<Transformator> transformators = transformatorDao.findAll();
		if(Utils.isCollectionNotEmpty(transformators)) {
			DefaultTableModel model = (DefaultTableModel) table.getModel();
			for (int i = 0; i < model.getRowCount(); i++) {
				model.removeRow(i);
			}
			for (Transformator transformator : transformators) {
				model.addRow(new Object[] { transformator.getType(),
						transformator.getsNom(), transformator.getUk(),
						transformator.getPk(), transformator.getuNom() });
			}
		}
	}
	
	
	public void updateTransformator(Long id, String type, Double sNom, Double uk, Double pk, Double uNom) {
		Transformator transformator = transformatorDao.findById(id);
		transformator.setType(type);
		transformator.setsNom(sNom);
		transformator.setUk(uk);
		transformator.setPk(pk);
		transformator.setuNom(uNom);
		transformatorDao.merge(transformator);
		
	}
	
	@Transactional
	public Long saveTransformator(String type, Double sNom, Double uk, Double pk, Double uNom) {
		Transformator transformator =  new Transformator();
		transformator.setType(type);
		transformator.setsNom(sNom);
		transformator.setUk(uk);
		transformator.setPk(pk);
		transformator.setuNom(uNom);
		transformatorDao.save(transformator);
		return transformator.getId();	
	}
	
	@Transactional
	public void deleteTransformator(Transformator transformator) {
		transformatorDao.delete(transformator);
	}
	
	@Transactional
	public void deleteTransformator(Long transformatorId) {
		Transformator transformator = transformatorDao.findById(transformatorId);
		transformatorDao.delete(transformator);
	}
}
